package com.example.cloud.service.business.medical.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.cloud.constants.CommonConstants;
import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.business.medical.ExecuteRecordRepository;
import com.example.cloud.dao.business.medical.TreatPlanCourseDetailsRepository;
import com.example.cloud.dao.business.medical.TreatPlanHomeProjectRepository;
import com.example.cloud.dao.business.medical.TreatPlanProductRepository;
import com.example.cloud.dao.business.medical.TreatPlanProjectRepository;
import com.example.cloud.dao.finance.ChargeDetailsRepository;
import com.example.cloud.dao.mongdb.basic.info.MongoProjectRepository;
import com.example.cloud.model.basic.Project;
import com.example.cloud.model.business.medical.ExecuteRecord;
import com.example.cloud.model.business.medical.TreatPlanCourseDetails;
import com.example.cloud.model.business.medical.TreatPlanHomeProject;
import com.example.cloud.model.business.medical.TreatPlanProduct;
import com.example.cloud.model.business.medical.TreatPlanProject;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.finance.ChargeDetails;
import com.example.cloud.model.member.Member;
import com.example.cloud.service.basic.info.MemberService;
import com.example.cloud.service.basic.info.ProjectService;
import com.example.cloud.service.business.medical.ExecuteService;
import com.example.cloud.service.business.medical.TreatPlanProjectService;
import com.example.cloud.utils.BusinessUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class TreatPlanProjectServiceImpl implements TreatPlanProjectService {

    private static final Logger logger = Logger.getLogger(TreatPlanProjectServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    private ExecuteService executeService;

    @Autowired
    private ExecuteRecordRepository executeRecordRepository;

    @Autowired
    private TreatPlanProjectRepository treatPlanProjectRepository;

    @Autowired
    private MongoProjectRepository mongoProjectRepository;

    @Autowired
    private TreatPlanProductRepository treatPlanProductRepository;

    @Autowired
    private TreatPlanCourseDetailsRepository treatPlanCourseDetailsRepository;

    @Autowired
    private TreatPlanHomeProjectRepository treatPlanHomeProjectRepository;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ChargeDetailsRepository chargeDetailsRepository;

    @Override
    public TreatPlanProject findOne(Long id) {
        return treatPlanProjectRepository.findOne(id);
    }

    @Override
    @Transactional
    public TreatPlanProject doSave(TreatPlanProject record) {
        if(record.getId() == null){
            record.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
        }
        BusinessUtil.appendRecord(record);
        return treatPlanProjectRepository.save(record);
    }

    @Override
    @Transactional
    public void batchInsert(List<TreatPlanProject> records, Long patientId) {
        for (TreatPlanProject record : records) {
            record.setId(null);
            record.setPatientId(patientId);
            // 设置会员信息
            ChargeDetails details = new ChargeDetails();
            Member member = memberService.findByPatientId(patientId);
            if(member != null){
                record.setMemberId(member.getId());
                details.setMemberId(member.getId());
            }
            record.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
            record.setTotalPrice(record.getPrice().multiply(new BigDecimal(record.getQuantity())));
            record.setCreationTime(null);
            BusinessUtil.appendRecord(record);
            treatPlanProjectRepository.save(record);

            // 生成收费
            generateChargeDetails(record, patientId, details);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void generateChargeDetails(TreatPlanProject record, Long patientId, ChargeDetails details){
        details.setPatientId(patientId);
        details.setBusinessId(record.getId());
        details.setBusinessType(StateConstants.CHARGE_BUSINESS_TYPE_ONE);
        details.setChargeType(StateConstants.CHARGE_CHARGE_TYPE_PROJECT);
        details.setItemId(record.getProjectId());
        details.setItemName(record.getProjectName());
        details.setQuantity(record.getQuantity());
        details.setPrice(record.getPrice());
        details.setTotalPrice(record.getTotalPrice());
        BusinessUtil.appendRecord(details);
        chargeDetailsRepository.save(details);
    }

    @Override
    @Transactional
    public Result doDeleteById(Long id) {
        Result result = new Result();
        result.setCode(CommonConstants.SUCCESS);
        result.setMsg("删除成功");
        // 校验删除条件
        boolean check = checkDelete(id);
        if(!check){
            result.setCode(CommonConstants.FAILURE);
            result.setMsg("购买成功后不能删除");
            return result;
        }
        // 物理删除
        treatPlanProjectRepository.delete(id);
        // 删除待收费
        chargeDetailsRepository.deleteByBusinessIdAndChargeType(id, StateConstants.CHARGE_CHARGE_TYPE_PROJECT);
        return result;
    }

    public boolean checkDelete(Long id){
        boolean check = true;
        TreatPlanProject record = treatPlanProjectRepository.findOne(id);
        // 已付款不能删除
        if(record.getChargeStatus() == StateConstants.CHARGE_STATUS_YES){
            check = false;
        }
        return check;
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        // 逻辑删除
        StringBuilder sql = new StringBuilder("update treat_plan_project set delete_flag = 1 where id in(:ids)");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("ids", ids);
        query.executeUpdate();
    }

    @Override
    @Transactional
    public void doExecute(Long id, int status, String context,TreatPlanProject record, List<TreatPlanProduct> records) {
        ExecuteRecord executeRecord = new ExecuteRecord();
        executeRecord.setPatientId(record.getPatientId());
        executeRecord.setComplaintId(record.getComplaintId());
        executeRecord.setOrderId(record.getId());
        executeRecord.setStatus(status);
        executeRecord.setTreatType(StateConstants.EXECUTE_TREAT_TYPE_ONE);
        executeRecord.setItemType(StateConstants.EXECUTE_ITEM_TYPE_PROJECT);
        executeRecord.setItemId(record.getProjectId());
        executeRecord.setItemName(record.getProjectName());
        executeRecord.setDoctorName(record.getCreatedBy());
        executeRecord.setDoctorRemark(record.getMedicalAdvice());
        executeRecord.setSource(record.getProjectName());
        executeRecord.setTotalCount(record.getQuantity());
        executeRecord.setMedicalTime(record.getCreationTime());
        executeRecord.setExecuteContent(context);
        executeRecord.setCreationTime(null);
        BusinessUtil.appendRecord(executeRecord);
        executeService.doSave(executeRecord);
        // 更新已执行次数
        if(status == StateConstants.EXECUTE_STATUS_YES){
            record.setExecute(record.getExecute() + 1);
            BusinessUtil.appendRecord(record);
            treatPlanProjectRepository.save(record);
        }
        // 更新处方产品
        for (TreatPlanProduct product : records) {
            product.setExecute(product.getExecute() + product.getUseQuantity());
            BusinessUtil.appendRecord(product);
            treatPlanProductRepository.save(product);
        }
    }

    @Override
    public JSONArray doFindDisposal(Long complaintId) {
        JSONArray resultList = new JSONArray();
        List<TreatPlanProject> list1 = treatPlanProjectRepository.findByComplaintIdAndDeleteFlag(complaintId, 0);
        for (TreatPlanProject planProject : list1) {
            Project project = mongoProjectRepository.findOne(planProject.getProjectId());
            if(project != null){
                JSONObject json = (JSONObject)JSON.toJSON(project);
                json.put("useMethod", planProject.getMedicalAdvice());
                // 总次数
                json.put("totalSize", planProject.getQuantity());
                // 已治疗次数
                json.put("treatSize", planProject.getExecute());
                // 总价格
                json.put("totalPrice", planProject.getTotalPrice());
                json.put("creationTime", planProject.getCreationTime());
                resultList.add(json);
            }
        }
        List<TreatPlanCourseDetails> list2 = treatPlanCourseDetailsRepository.findByComplaintIdAndDeleteFlag(complaintId,0);
        for (TreatPlanCourseDetails courseDetails : list2) {
            Project project = mongoProjectRepository.findOne(courseDetails.getItemId());
            if(project != null){
                JSONObject json = (JSONObject)JSON.toJSON(project);
                json.put("useMethod", courseDetails.getMedicalAdvice());
                // 总次数
                json.put("totalSize", courseDetails.getQuantity());
                // 总价格
                json.put("totalPrice", courseDetails.getTotalPrice());
                // 已治疗次数
                json.put("treatSize", courseDetails.getExecute());
                json.put("creationTime", courseDetails.getCreationTime());
                resultList.add(json);
            }
        }
        List<TreatPlanHomeProject> list3 = treatPlanHomeProjectRepository.findByComplaintIdAndDeleteFlag(complaintId,0);
        for (TreatPlanHomeProject homeProject : list3) {
            Project project = mongoProjectRepository.findOne(homeProject.getProjectId());
            if(project != null){
                JSONObject json = (JSONObject)JSON.toJSON(project);
                json.put("useMethod", homeProject.getMedicalAdvice());
                // 总次数
                json.put("totalSize", homeProject.getQuantity());
                // 总价格
                json.put("totalPrice", homeProject.getTotalPrice());
                // 已治疗次数
                json.put("treatSize", homeProject.getExecute());
                json.put("creationTime", homeProject.getCreationTime());
                resultList.add(json);
            }
        }
        return resultList;
    }
}
